﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WpfAppWebSocket1
{
    public delegate void ReceivedHandler(string message);

    internal class WebSocketClient1
    {
        public event ReceivedHandler Received;

        ClientWebSocket clientWebSocket = new ClientWebSocket();
        public async Task Connect(string serverUrl)
        {
            try
            {
                await clientWebSocket.ConnectAsync(new Uri(serverUrl), CancellationToken.None);

                await ReceiveMessage(clientWebSocket);

                // 发送消息到服务器
                string message = "Hello, server!";
                await SendMessage(clientWebSocket, message);

                clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closed by the client", CancellationToken.None);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                throw;
            }
        }

        private async Task ReceiveMessage(ClientWebSocket clientWebSocket)
        {
            byte[] buffer = new byte[1024];
            while (clientWebSocket.State == WebSocketState.Open)
            {
                WebSocketReceiveResult result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.CloseStatus != null)
                    break;

                string receivedMessage = System.Text.Encoding.Default.GetString(buffer, 0, result.Count);
                // 处理从服务器接收到的消息
                if (Received != null)
                    Received(receivedMessage);
            }
        }

        private async Task SendMessage(ClientWebSocket clientWebSocket, string message)
        {
            byte[] buffer = System.Text.Encoding.Default.GetBytes(message);
            await clientWebSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
        }

        public async Task SendMessage(string message)
        {
            byte[] buffer = System.Text.Encoding.Default.GetBytes(message);
            await clientWebSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
        }
    }
}
